/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import com.sun.istack.NotNull;
import me.zhengjie.modules.biz.domain.*;
import me.zhengjie.modules.biz.repository.LabRepository;
import me.zhengjie.modules.biz.repository.SensorRepository;
import me.zhengjie.modules.biz.service.dto.*;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.SensorLogRepository;
import me.zhengjie.modules.biz.service.SensorLogService;
import me.zhengjie.modules.biz.service.mapstruct.SensorLogMapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.lang.System;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class SensorLogServiceImpl implements SensorLogService {

    private final SensorLogRepository sensorLogRepository;
    private final SensorLogMapper sensorLogMapper;
    private final SensorRepository sensorRepository;
    private final LabRepository labRepository;


    @Override
    public Map<String,Object> queryAll(SensorLogQueryCriteria criteria, Pageable pageable){
        Specification<SensorLog> specification = (Specification<SensorLog>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getType() == null){
                predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 1)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 3))));
            }else {
                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
            }
            if (criteria.getId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("id"),  criteria.getId() ));
            }
            if (criteria.getCreatedAt() != null){
                predicates.add(criteriaBuilder.equal(root.get("createdAt"),criteria.getCreatedAt()));
            }
            if (criteria.getLogType()!= null){
                predicates.add(criteriaBuilder.equal(root.get("logType"),criteria.getLogType()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<SensorLog> page = sensorLogRepository.findAll(specification, pageable);
        Page<SensorLogDto> dto = page.map(sensorLogMapper::toDto);
        List<SensorLogDto> resultDto = dto.getContent();
        for (SensorLogDto sensorLogDto : resultDto) {
            if (Objects.nonNull(sensorLogDto.getSensorId())) {
                Sensor sensor = sensorRepository.findById(sensorLogDto.getSensorId()).orElseGet(Sensor::new);
                if (Objects.nonNull(sensor.getId())) {
                    sensorLogDto.setName(sensor.getName());
                }
            }
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public Map<String, Object> queryEnvironment(SensorLogQueryCriteria criteria, Pageable pageable) {
        Specification<SensorLog> specification = (Specification<SensorLog>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getType() == null){
                predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 1)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 3))));
            }else {
                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
            }
            if (criteria.getId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("id"), criteria.getId()));
            }
            if (criteria.getCreatedAt() != null){
                predicates.add(criteriaBuilder.equal(root.get("createdAt"),criteria.getCreatedAt()));
            }
            if (criteria.getLogType()!= null){
                predicates.add(criteriaBuilder.equal(root.get("logType"),criteria.getLogType()));
            }
            predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 1)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 3))));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        Page<SensorLog> page = sensorLogRepository.findAll(specification, pageable);
        Page<SensorLogDto> dto = page.map(sensorLogMapper::toDto);
        List<SensorLogDto> resultDto = dto.getContent();
        for (SensorLogDto sensorLogDto : resultDto) {
            if (Objects.nonNull(sensorLogDto.getSensorId())) {
                Sensor sensor = sensorRepository.findById(sensorLogDto.getSensorId()).orElseGet(Sensor::new);
                if (Objects.nonNull(sensor.getId())) {
                    sensorLogDto.setName(sensor.getName());
                }
            }
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<SensorLogDto> queryAll(SensorLogQueryCriteria criteria){
        return sensorLogMapper.toDto(sensorLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SensorLogDto findById(Integer id) {
        SensorLog sensorLog = sensorLogRepository.findById(id).orElseGet(SensorLog::new);
        ValidationUtil.isNull(sensorLog.getId(),"SensorLog","id",id);
        return sensorLogMapper.toDto(sensorLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SensorLogDto create(SensorLog resources) {
        return sensorLogMapper.toDto(sensorLogRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SensorLog resources) {
        SensorLog sensorLog = sensorLogRepository.findById(resources.getId()).orElseGet(SensorLog::new);
        ValidationUtil.isNull( sensorLog.getId(),"SensorLog","id",resources.getId());
        sensorLog.copy(resources);
        sensorLogRepository.save(sensorLog);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            sensorLogRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SensorLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SensorLogDto sensorLog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("传感器", sensorLog.getName());
            map.put("传感器历史数据", sensorLog.getData());
            String logType = "";
            switch (sensorLog.getLogType()) {
                case 0:
                    logType = "普通日志";
                    break;
                case 1:
                    logType = "报警日志";
                    break;
            }
            map.put("日志类型", logType);
            if (sensorLog.getType() == 5) {

            } else {
                map.put("时间",  sensorLog.getCreatedAt());
            }

            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void queryAllByTime(ArrayList<Integer> sensorId) {
        ArrayList<Integer> idList = sensorLogRepository.findAllSensorId();
        idList.retainAll(sensorId);
        HashMap<Integer,String> idNameMap = new HashMap<>();
        HashMap<Integer,Integer> idTypeMap = new HashMap<>();
        HashMap<Integer,String> idLabMap = new HashMap<>();
        for (int sid:idList) {
            Sensor sensor = sensorRepository.getSensor(sid);
            Lab lab = labRepository.getLab(sensor.getLabId());
            idNameMap.put(sid,sensor.getName());
            idTypeMap.put(sid,sensor.getType());
            idLabMap.put(sid,lab.getName());
        }
    }

    @Override
    public Map<String, Object> charts(HttpServletRequest request) {
        if (request.getParameter("labId")==null && request.getParameter("startTime")==null && request.getParameter("type")==null){
            Date date_early;
            Date date_night;
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllLogId();
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());
                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<7;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }

                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        if (request.getParameter("labId")!=null && request.getParameter("startTime")==null && request.getParameter("type")==null){
            Date date_early;
            Date date_night;
            int labId = Integer.parseInt(request.getParameter("labId"));
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllByLabId(labId);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<7;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (request.getParameter("labId")==null && request.getParameter("startTime")!=null && request.getParameter("type")==null){
            Date date_early;
            Date date_night;
            String early = request.getParameter("startTime");
            String night = request.getParameter("endTime");
//            int labId = Integer.parseInt(request.getParameter("labId"));
            Long days = (Long.parseLong(night)-Long.parseLong(early))/(1000*60*60*24);
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 23:59:59"));

                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllLogId();
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<=days;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (request.getParameter("labId")==null && request.getParameter("startTime")==null && request.getParameter("type")!=null){
            Date date_early;
            Date date_night;
            int type = Integer.parseInt(request.getParameter("type"));
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllByType(type);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();
                    for (int i=0;i<7;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);

                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (request.getParameter("labId")!=null && request.getParameter("startTime")!=null && request.getParameter("type")==null){
            Date date_early;
            Date date_night;
            String early = request.getParameter("startTime");
            String night = request.getParameter("endTime");
            int labId = Integer.parseInt(request.getParameter("labId"));

            Long days = (Long.parseLong(night)-Long.parseLong(early))/(1000*60*60*24);
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllByLabId(labId);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<=days;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (request.getParameter("labId")!=null && request.getParameter("startTime")==null && request.getParameter("type")!=null){
            Date date_early;
            Date date_night;
            int type = Integer.parseInt(request.getParameter("type"));
            int labId = Integer.parseInt(request.getParameter("labId"));
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllBySensorIdByLabIdType(labId,type);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<7;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (request.getParameter("labId")==null && request.getParameter("startTime")!=null && request.getParameter("type")!=null){
            Date date_early;
            Date date_night;
            String early = request.getParameter("startTime");
            String night = request.getParameter("endTime");
            int type = Integer.parseInt(request.getParameter("type"));
            Long days = (Long.parseLong(night)-Long.parseLong(early))/(1000*60*60*24);
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllByType(type);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<=days;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (request.getParameter("labId")!=null && request.getParameter("startTime")!=null && request.getParameter("type")!=null){
            Date date_early;
            Date date_night;
            String early = request.getParameter("startTime");
            String night = request.getParameter("endTime");
            int labId = Integer.parseInt(request.getParameter("labId"));
            int type = Integer.parseInt(request.getParameter("type"));
            Long days = (Long.parseLong(night)-Long.parseLong(early))/(1000*60*60*24);
            Map<String,Object> chartsData = new HashMap<>();
            try {
                ArrayList<String> dateList = new ArrayList<>();
                date_early = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 00:00:00"));
                date_night = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateFormatUtils.format(new Date(Long.parseLong(night)), "yyyy-MM-dd 23:59:59"));
                Calendar cal = Calendar.getInstance();
                cal.setTime(date_early);
                long timestamp_early = cal.getTimeInMillis();
                cal.setTime(date_night);
                long timestamp_night = cal.getTimeInMillis();
                List<Integer> sensorIds = sensorRepository.findAllBySensorIdByLabIdType(labId,type);
                ArrayList<SensorLogChartDataDto> sensorLogChartDataDtoArrayList = new ArrayList<>();
                int flag = 0;
                for (Integer sensorId:sensorIds) {
                    List<SensorLog> sensorLogList = sensorLogRepository.findAllBySensorIdEnvironment(sensorId);
                    SensorLogChartDataDto sensorLogChartDataDto = new SensorLogChartDataDto();
                    Sensor sensor = sensorRepository.findById(sensorId).orElseGet(Sensor::new);
                    sensorLogChartDataDto.setName(sensor.getName());
                    sensorLogChartDataDto.setLabId(sensor.getLabId());

                    System.out.println(sensor.getName());
                    long times_early = timestamp_early;
                    long times_night = timestamp_night;
                    ArrayList<Float> data = new ArrayList<>();

                    for (int i=0;i<=days;i++){
                        float num = 0;
                        int count = 0;
                        for (SensorLog sensorLog:sensorLogList) {
                            java.sql.Date dateTime = new java.sql.Date(sensorLog.getCreatedAt().getTime());
                            cal = Calendar.getInstance();
                            cal.setTime(dateTime);
                            long current_time = cal.getTimeInMillis();
                            if (current_time<=times_night && current_time>=times_early){
                                num+=sensorLog.getData();
                                count++;
                            }
                        }
                        if (count==0){
                            data.add((float) 0);
                        }else {
                            data.add(num/count);
                        }
                        if (flag==0){
                            dateList.add(conversionTime(String.valueOf(times_early)));
                        }
                        times_early -= 24*60*60*1000;
                        times_night -= 24*60*60*1000;
                    }flag++;
                    sensorLogChartDataDto.setData(data);
                    sensorLogChartDataDtoArrayList.add(sensorLogChartDataDto);
                }
                chartsData.put("date",dateList);
                chartsData.put("data",sensorLogChartDataDtoArrayList);
                return chartsData;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return null;
    }



    //传入时间戳即可
    private String conversionTime(String timeStamp) {
        //yyyy-MM-dd HH:mm:ss 转换的时间格式  可以自定义
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //转换
        return sdf.format(new Date(Long.parseLong(timeStamp)));
    }



//    @Override
//    public Map<String, Object> querySensorLogByType(SensorLogQueryCriteria criteria, Pageable pageable) {
//        Specification<Sensor> specification = (Specification<Sensor>) (root, query, criteriaBuilder) -> {
//            List<Predicate> predicates = new ArrayList<Predicate>();
//            if (criteria.getName() != null) {
//                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
//            }
//            if (criteria.getDataType() != null) {
//                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
//            }
//            predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 1)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 3))));
//            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
//        };
//        Page<Sensor> page = sensorRepository.findAll(specification, pageable);
//        Page<SensorDto> dto = page.map(sensorMapper::toDto);
//        List<SensorDto> resultDto = dto.getContent();
//        for (SensorDto sensorDto:resultDto) {
//            Lab lab = labRepository.findById(sensorDto.getLabId()).orElseGet(Lab::new);
//            sensorDto.setLabName(lab.getName());
//        }
//        return PageUtil.toPage(dto);
//    }
}
